package com.hsmw.api.controller.integral;


import cn.hutool.log.Log;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hsmw.api.config.NoRepeatSubmit;
import com.hsmw.api.config.jwt.LoginUser;
import com.hsmw.api.controller.pub.RedisCache;
import com.hsmw.api.mapper.HsmwDriverMapper;
import com.hsmw.api.mapper.HsmwGoodsOrderMapper;
import com.hsmw.api.mapper.HsmwPointsDetailsMapper;
import com.hsmw.api.service.HsmwDriverService;
import com.hsmw.api.service.HsmwIntegraGoodsSkuService;
import com.hsmw.api.service.HsmwIntegralGoodsService;
import com.htn.common.core.base.DataResponse;
import com.htn.common.core.constant.CommonConstants;
import com.htn.common.core.utils.DateUtil;
import com.htn.common.core.utils.StringUtils;
import com.hsmw.domain.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.junit.Test;
import org.junit.internal.runners.statements.Fail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;
import com.hsmw.common.base.BaseController;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author tjy
 * @since 2021-07-16
 */
@Api(tags = "积分商城商品信息")
@RestController
@RequestMapping("/hsmw/goods/")
public class HsmwIntegralGoodsController extends BaseController<HsmwIntegralGoodsService, HsmwIntegralGoods> {



    @Autowired
    private HsmwDriverService hsmwDriverService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private HsmwIntegralGoodsService goodsService;

    @Autowired
    private HsmwDriverMapper hsmwDriverMapper;

    @Autowired
    private HsmwPointsDetailsMapper hsmwPointsDetailsMapper;


    @Autowired
    private HsmwIntegralGoodsService hsmwIntegralGoodsService;

    @Autowired
    private HsmwGoodsOrderMapper hsmwGoodsOrderMapper;

    @Autowired
    private HsmwIntegraGoodsSkuService hsmwIntegraGoodsSkuService;



    @ApiOperation(value = "每日签到", notes = "每日签到", produces = "application/json")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "司机id",dataType = "String"),
            @ApiImplicitParam(name = "integral",value = "商品积分",dataType = "Long")
    })
    @PostMapping("updateDriverIntegralById")
    @NoRepeatSubmit
    public DataResponse updateDriverIntegralById(String id,Long integral) {

        if (StringUtils.isBlank(id) || integral == null) {
            return new DataResponse(CommonConstants.ResponseStatus.FAIL, "id或者积分传递错误");
        }

        String key = "driver:integral:" + id;
        String keys = "driver:count:" + id;


        HsmwUserDriver hsmwUserDriver = hsmwDriverMapper.selectById(id);
        if (hsmwUserDriver != null) {
            long DriIntegral = Long.parseLong(hsmwUserDriver.getDriverIntegral());
            hsmwUserDriver.setDriverIntegral(String.valueOf(integral + DriIntegral));
        }
        hsmwDriverMapper.updateById(hsmwUserDriver);
        HsmwPointsDetails hsmwPointsDetails = new HsmwPointsDetails();
        hsmwPointsDetails.setTypeIntegral(new BigDecimal(integral));
        hsmwPointsDetails.setType("每日签到");
        hsmwPointsDetails.setDriverId(id);
        hsmwPointsDetailsMapper.insert(hsmwPointsDetails);
        Long nowToNextDaySeconds = DateUtil.getNowToNextDaySeconds();
        redisTemplate.opsForValue().set(key, LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        redisTemplate.opsForValue().increment(keys, 1);


        return new DataResponse(CommonConstants.ResponseStatus.SUCCESS);
    }


    @ApiOperation(value = "查询签到状态", notes = "查询签到状态", produces = "application/json")
    @ApiImplicitParam(name = "id", value = "司机id", dataType = "String")
    @PostMapping("findDriverIntegralStatus")
    public DataResponse findDriverIntegralStatus(String id) {

        if(StringUtils.isBlank(id)){
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"id为空");
        }
        String key = "driver:integral:"+id;
        String keys = "driver:count:"+id;
        String shareKey = "driver:share:"+id;

        /*Long expire = redisTemplate.opsForValue().getOperations().getExpire("noRepeatSubmit:web-HU162634196680aa3c76b6a7:192.168.0.100:/hsmw/goods/updateDriverIntegralById");
        System.err.println(expire);*/
        String s = redisTemplate.opsForValue().get(keys);
        Integer count = Integer.parseInt(s == null ? "0" : s);
        Boolean flag = redisTemplate.hasKey(key);
        HsmwUserDriver hsmwUserDriver = hsmwDriverMapper.selectById(id);

        Boolean shareFlag = redisTemplate.hasKey(shareKey);


        Map map = new HashMap();
        map.put("integral",hsmwUserDriver.getDriverIntegral());
        map.put("shareFlag",shareFlag);
        if(flag){
            String value = (String) redisTemplate.opsForValue().get(key);
            LocalDate beginDateTime = LocalDate.parse(value, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            if(beginDateTime.isEqual(LocalDate.now())){
                map.put("count",count == null ? 0 : count );
                map.put("flag",true);
                return new DataResponse(CommonConstants.ResponseStatus.SUCCESS,map);
            }else {
                map.put("flag",false);
                LocalDate localDate = LocalDate.now().plusDays(-1);
                if(localDate.isEqual(beginDateTime)){
                    map.put("count",count == null ? 0 : count );
                }else {
                    map.put("count", 0);
                    redisTemplate.delete(keys);
                    redisTemplate.opsForValue().increment(keys, 0);
                }
                return new DataResponse(CommonConstants.ResponseStatus.SUCCESS,map);
            }

        }else {
            map.put("flag",false);
            return new DataResponse(CommonConstants.ResponseStatus.SUCCESS,map);
        }
    }




    @ApiOperation(value = "查询商品信息", notes = "查询商品信息", produces = "application/json")
    @PostMapping("findGoodsList")
    public DataResponse findGoodsList(@RequestBody HsmwIntegralGoods hsmwIntegralGoods){

        List<HsmwIntegralGoods> list  = hsmwIntegralGoodsService.findGoodsList(hsmwIntegralGoods);

        return new DataResponse(list);
    }


    @ApiOperation(value = "根据商品id查询商品详细信息", notes = "根据商品id查询商品详细信息", produces = "application/json")
    @ApiImplicitParam(name = "商品id", value = "goodsId",dataType = "String")
    @PostMapping("findGoodsInfoById")
    public DataResponse findGoodsInfoById(String goodsId){

        if(StringUtils.isBlank(goodsId)){
            new DataResponse(CommonConstants.ResponseStatus.FAIL,"商品id不可为空");
        }

        return new DataResponse(hsmwIntegralGoodsService.findGoodsInfoById(goodsId));
    }


    @ApiOperation(value = "根据商品id查询尺码颜色", notes = "根据商品id查询尺码颜色", produces = "application/json")
    @ApiImplicitParam(name = "商品id", value = "goodsId",dataType = "String")
    @PostMapping("selectGoodsPageInfo")
    public DataResponse selectGoodsPageInfo(String goodsId){
        if(StringUtils.isBlank(goodsId)){
            new DataResponse(CommonConstants.ResponseStatus.FAIL,"商品id不可为空");
        }

        return new DataResponse(hsmwIntegralGoodsService.selectGoodsPageInfo(goodsId));
    }



    /**
     * 兑换商品 扣减积分
     * @param hsmwGoodsOrder
     * @return
     */
    @ApiOperation(value = "兑换商品", notes = "兑换商品", produces = "application/json")
    @PostMapping("exchangeGoods")
    public DataResponse exchangeGoods(@RequestBody HsmwGoodsOrder hsmwGoodsOrder){

        if(StringUtils.isNotBlank(hsmwGoodsOrder.getValidationCode())){
            if(!StringUtils.equals(hsmwGoodsOrder.getValidationCode(),"666888")){
                return new DataResponse(CommonConstants.ResponseStatus.FAIL,"请输入正确的效验码");
            }
        }
        Map map = new HashMap();
        if(hsmwGoodsOrder == null){
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"参数不可为空");
        }
        hsmwGoodsOrder.setCreateTime(LocalDateTime.now());

        HsmwUserDriver hsmwUserDriver = hsmwDriverMapper.selectById(hsmwGoodsOrder.getDriverId());
        long driIntrrgral = Long.parseLong(hsmwUserDriver.getDriverIntegral());
        long Points = Long.parseLong(hsmwGoodsOrder.getPoints());

        String goodsId = hsmwGoodsOrder.getGoodsId();
        String skuId = hsmwGoodsOrder.getSelectSpecificationsId();
        //根据goodsid查询商品信息表
        HsmwIntegralGoods goods = hsmwIntegralGoodsService.getById(goodsId);
        // 根据skuid 查询sku信息表
        HsmwIntegraGoodsSku goodsSku = hsmwIntegraGoodsSkuService.getById(skuId);
        // 兑换的数量
        long stock =hsmwGoodsOrder.getStock();
        //剩余的库存
        Long skuStock = Long.parseLong(goodsSku.getStock());
        Long integral = stock * Points;
        if(driIntrrgral < integral){
            map.put("info","积分不足,请检查");
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,map);
        }
        if(skuStock <= 0 || skuStock < stock){
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"库存不足，无法兑换");
        }

        hsmwGoodsOrder.setSelectSpecifications(goodsSku.getGoodsColor()+"/"+goodsSku.getGoodsSize());
        hsmwGoodsOrder.setGoodsName(goods.getGoodsName());
        hsmwGoodsOrder.setConsumePoints(String.valueOf(integral));
        hsmwGoodsOrder.setMainPicture(goods.getGoodsImage());
        hsmwGoodsOrder.setGoodsAmount(String.valueOf(stock));

        // 修改库存信息
        goodsSku.setStock(String.valueOf(skuStock - stock));
        hsmwIntegraGoodsSkuService.updateById(goodsSku);
        hsmwGoodsOrderMapper.insert(hsmwGoodsOrder);
        hsmwUserDriver.setDriverIntegral(String.valueOf(driIntrrgral-integral));
        hsmwDriverMapper.updateById(hsmwUserDriver);

        HsmwPointsDetails hsmwPointsDetails = new HsmwPointsDetails();
        hsmwPointsDetails.setTypeIntegral(new BigDecimal(integral * -1));
        hsmwPointsDetails.setType("购物消费");
        hsmwPointsDetails.setDriverId(hsmwGoodsOrder.getDriverId());
        hsmwPointsDetailsMapper.insert(hsmwPointsDetails);
        String driverIntegral = hsmwUserDriver.getDriverIntegral();
        String orderId = hsmwGoodsOrder.getId();
        map.put("driverIntegral",driverIntegral);
        map.put("orderId",orderId);
        return new DataResponse(CommonConstants.ResponseStatus.SUCCESS,map);
    }


    @ApiOperation(value = "根据订单id查询订单信息", notes = "根据订单id查询订单信息", produces = "application/json")
    @ApiImplicitParam(name = "订单id",value = "id",dataType = "String")
    @PostMapping("findOrderInfoById")
    public DataResponse findOrderInfoById(String id){

        HsmwGoodsOrder hsmwGoodsOrder = hsmwGoodsOrderMapper.selectById(id);

        return new DataResponse(hsmwGoodsOrder);

    }


    @ApiOperation(value = "赚积分状态", notes = "赚积分状态", produces = "application/json")
    @ApiImplicitParam(name = "司机id",value = "id",dataType = "String")
    @PostMapping("findDriverIntegralStatusById")
    public DataResponse findDriverIntegralStatusById(String id){


        return new DataResponse(hsmwIntegralGoodsService.findDriverIntegralStatusById(id));
    }

}

